3 * Functions related to the output of file content.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 use Wikimedia\Timestamp\ConvertibleTimestamp
;
25 * Functions related to the output of file content
29 class HTTPFileStreamer
{
33 protected $obResetFunc;
35 protected $streamMimeFunc;
37 // Do not send any HTTP headers unless requested by caller (e.g. body only)
38 const STREAM_HEADLESS
= 1;
39 // Do not try to tear down any PHP output buffers
40 const STREAM_ALLOW_OB
= 2;
43 * Takes HTTP headers in a name => value format and converts them to the weird format
44 * expected by stream().
45 * @param string[] $headers
46 * @return array[] [ $headers, $optHeaders ]
49 public static function preprocessHeaders( $headers ) {
52 foreach ( $headers as $name => $header ) {
53 $nameLower = strtolower( $name );
54 if ( in_array( $nameLower, [ 'range', 'if-modified-since' ], true ) ) {
55 $optHeaders[$nameLower] = $header;
57 $rawHeaders[] = "$name: $header";
60 return [ $rawHeaders, $optHeaders ];
64 * @param string $path Local filesystem path to a file
65 * @param array $params Options map, which includes:
66 * - obResetFunc : alternative callback to clear the output buffer
67 * - streamMimeFunc : alternative method to determine the content type from the path
69 public function __construct( $path, array $params = [] ) {
71 $this->obResetFunc
= $params['obResetFunc'] ??
[ __CLASS__
, 'resetOutputBuffers' ];
72 $this->streamMimeFunc
= $params['streamMimeFunc'] ??
[ __CLASS__
, 'contentTypeFromPath' ];
76 * Stream a file to the browser, adding all the headings and fun stuff.
77 * Headers sent include: Content-type, Content-Length, Last-Modified,
78 * and Content-Disposition.
80 * @param array $headers Any additional headers to send if the file exists
81 * @param bool $sendErrors Send error messages if errors occur (like 404)
82 * @param array $optHeaders HTTP request header map (e.g. "range") (use lowercase keys)
83 * @param int $flags Bitfield of STREAM_* constants
84 * @return bool Success
86 public function stream(
87 $headers = [], $sendErrors = true, $optHeaders = [], $flags = 0
89 // Don't stream it out as text/html if there was a PHP error
90 if ( ( ( $flags & self
::STREAM_HEADLESS
) == 0 ||
$headers ) && headers_sent() ) {
91 echo "Headers already sent, terminating.\n";
95 $headerFunc = ( $flags & self
::STREAM_HEADLESS
)
96 ?
function ( $header ) {
99 : function ( $header ) {
100 is_int( $header ) ? HttpStatus
::header( $header ) : header( $header );
103 Wikimedia\
suppressWarnings();
104 $info = stat( $this->path
);
105 Wikimedia\restoreWarnings
();
107 if ( !is_array( $info ) ) {
109 self
::send404Message( $this->path
, $flags );
114 // Send Last-Modified HTTP header for client-side caching
115 $mtimeCT = new ConvertibleTimestamp( $info['mtime'] );
116 $headerFunc( 'Last-Modified: ' . $mtimeCT->getTimestamp( TS_RFC2822
) );
118 if ( ( $flags & self
::STREAM_ALLOW_OB
) == 0 ) {
119 call_user_func( $this->obResetFunc
);
122 $type = call_user_func( $this->streamMimeFunc
, $this->path
);
123 if ( $type && $type != 'unknown/unknown' ) {
124 $headerFunc( "Content-type: $type" );
126 // Send a content type which is not known to Internet Explorer, to
127 // avoid triggering IE's content type detection. Sending a standard
128 // unknown content type here essentially gives IE license to apply
129 // whatever content type it likes.
130 $headerFunc( 'Content-type: application/x-wiki' );
133 // Don't send if client has up to date cache
134 if ( isset( $optHeaders['if-modified-since'] ) ) {
135 $modsince = preg_replace( '/;.*$/', '', $optHeaders['if-modified-since'] );
136 if ( $mtimeCT->getTimestamp( TS_UNIX
) <= strtotime( $modsince ) ) {
137 ini_set( 'zlib.output_compression', 0 );
143 // Send additional headers
144 foreach ( $headers as $header ) {
145 header( $header ); // always use header(); specifically requested
148 if ( isset( $optHeaders['range'] ) ) {
149 $range = self
::parseRange( $optHeaders['range'], $info['size'] );
150 if ( is_array( $range ) ) {
152 $headerFunc( 'Content-Length: ' . $range[2] );
153 $headerFunc( "Content-Range: bytes {$range[0]}-{$range[1]}/{$info['size']}" );
154 } elseif ( $range === 'invalid' ) {
157 $headerFunc( 'Cache-Control: no-cache' );
158 $headerFunc( 'Content-Type: text/html; charset=utf-8' );
159 $headerFunc( 'Content-Range: bytes */' . $info['size'] );
162 } else { // unsupported Range request (e.g. multiple ranges)
164 $headerFunc( 'Content-Length: ' . $info['size'] );
168 $headerFunc( 'Content-Length: ' . $info['size'] );
171 if ( is_array( $range ) ) {
172 $handle = fopen( $this->path
, 'rb' );
175 fseek( $handle, $range[0] );
176 $remaining = $range[2];
177 while ( $remaining > 0 && $ok ) {
178 $bytes = min( $remaining, 8 * 1024 );
179 $data = fread( $handle, $bytes );
180 $remaining -= $bytes;
181 $ok = ( $data !== false );
188 return readfile( $this->path
) !== false; // faster
195 * Send out a standard 404 message for a file
197 * @param string $fname Full name and path of the file to stream
198 * @param int $flags Bitfield of STREAM_* constants
201 public static function send404Message( $fname, $flags = 0 ) {
202 if ( ( $flags & self
::STREAM_HEADLESS
) == 0 ) {
203 HttpStatus
::header( 404 );
204 header( 'Cache-Control: no-cache' );
205 header( 'Content-Type: text/html; charset=utf-8' );
207 $encFile = htmlspecialchars( $fname );
208 $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
209 echo "<!DOCTYPE html><html><body>
210 <h1>File not found</h1>
211 <p>Although this PHP script ($encScript) exists, the file requested for output
212 ($encFile) does not.</p>
218 * Convert a Range header value to an absolute (start, end) range tuple
220 * @param string $range Range header value
221 * @param int $size File size
222 * @return array|string Returns error string on failure (start, end, length)
225 public static function parseRange( $range, $size ) {
227 if ( preg_match( '#^bytes=(\d*)-(\d*)$#', $range, $m ) ) {
228 list( , $start, $end ) = $m;
229 if ( $start === '' && $end === '' ) {
230 $absRange = [ 0, $size - 1 ];
231 } elseif ( $start === '' ) {
232 $absRange = [ $size - $end, $size - 1 ];
233 } elseif ( $end === '' ) {
234 $absRange = [ $start, $size - 1 ];
236 $absRange = [ $start, $end ];
238 if ( $absRange[0] >= 0 && $absRange[1] >= $absRange[0] ) {
239 if ( $absRange[0] < $size ) {
240 $absRange[1] = min( $absRange[1], $size - 1 ); // stop at EOF
241 $absRange[2] = $absRange[1] - $absRange[0] +
1;
243 } elseif ( $absRange[0] == 0 && $size == 0 ) {
244 return 'unrecognized'; // the whole file should just be sent
249 return 'unrecognized';
252 protected static function resetOutputBuffers() {
253 while ( ob_get_status() ) {
254 if ( !ob_end_clean() ) {
255 // Could not remove output buffer handler; abort now
256 // to avoid getting in some kind of infinite loop.
263 * Determine the file type of a file based on the path
265 * @param string $filename Storage path or file system path
266 * @return null|string
268 protected static function contentTypeFromPath( $filename ) {
269 $ext = strrchr( $filename, '.' );
270 $ext = $ext === false ?
'' : strtolower( substr( $ext, 1 ) );
283 return 'unknown/unknown';